//
//  MePointViewController.m
//  CarUser
//
//  Created by 王森林 on 2019/1/18.
//  Copyright © 2019年 王森林. All rights reserved.
//

#import "MePointViewController.h"
#import "InsurancePointCell.h"
#import "UserRes.h"
#import "MaintainPointCell.h"
@interface MePointViewController ()
@property (nonatomic, strong) NSMutableArray *InsuranceAry;
@property (nonatomic, strong) NSMutableArray *MaintainAry;
@end

@implementation MePointViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"我的预约";
    [self createUI];
    [self fetchDataWithNet];
    self.mainTableView.mj_header = [Custom_Mjfresh mj_customMjfreshHeaderSetting:^{
        [self fetchDataWithNet];
    }];
    // Do any additional setup after loading the view.
}

- (void)fetchDataWithNet
{
    
    //  保险预约列表
    UserRes *user = [CommonMethod getUser];
    if (!user) {
        [[NSNotificationCenter defaultCenter]postNotificationName:NotificationCenterName_AlertLoginVC object:nil];
        return;
    }
    NSDictionary *params = @{
                             @"FKEY":[CommonMethod createMD5Key:@"TOKEN"],
                             @"TOKEN":user.TOKEN,
                             @"USERNAME":user.mobile
                             
                             };
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [SVProgressHUD showWithStatus:nil];
    });
    
    [[ZY_AfnNetManager shareInstance]postWithURL:Car_API_46 params:params md5Paraname:nil success:^(id  _Nullable response) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
        });
         [self.mainTableView.mj_header endRefreshing];
        [self.InsuranceAry removeAllObjects];
        NSDictionary  *dict = response;
        NSArray *ary = [dict objectForKey:@"list"];
         if (ary != nil && ![ary isKindOfClass:[NSNull class]] && ary.count != 0) {
          self.InsuranceAry = [NSMutableArray arrayWithArray:[dict objectForKey:@"list"]];
         } else {
             
             
         }
        
      
        [self fetchMaintainDataWithNet];
//        [self.mainTableView reloadData];
        
        
        
    } fail:^(NSError * _Nonnull error) {
        dispatch_async(dispatch_get_main_queue(), ^{
             [self.mainTableView.mj_header endRefreshing];
            [SVProgressHUD showErrorWithStatus:error.localizedDescription];
        });
        
    }];
    
}

- (void)fetchMaintainDataWithNet
{
    
    //  保险预约列表
    UserRes *user = [CommonMethod getUser];
    if (!user) {
        [[NSNotificationCenter defaultCenter]postNotificationName:NotificationCenterName_AlertLoginVC object:nil];
        return;
    }
    NSDictionary *params = @{
                             @"FKEY":[CommonMethod createMD5Key:@"TOKEN"],
                             @"TOKEN":user.TOKEN,
                             @"USERNAME":user.mobile
                             
                             };
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [SVProgressHUD showWithStatus:nil];
    });
    
    [[ZY_AfnNetManager shareInstance]postWithURL:Car_API_49 params:params md5Paraname:nil success:^(id  _Nullable response) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
        });
         [self.mainTableView.mj_header endRefreshing];
        NSDictionary  *dict = response;
        [self.MaintainAry removeAllObjects];
        NSArray *ary = [dict objectForKey:@"list"];
        if (ary != nil && ![ary isKindOfClass:[NSNull class]] && ary.count != 0) {
            self.MaintainAry = [NSMutableArray arrayWithArray:[dict objectForKey:@"list"]];
        } else {
            
            
        }
        
        if (self.MaintainAry.count + self.InsuranceAry.count == 0) {
              [self showNodataView:self.mainTableView.centerY-150 withView:self.mainTableView];
        } else {
             [self hideNoDataView];
        }
        
        [self.mainTableView reloadData];
        
        
        
    } fail:^(NSError * _Nonnull error) {
        dispatch_async(dispatch_get_main_queue(), ^{
             [self.mainTableView.mj_header endRefreshing];
            [SVProgressHUD showErrorWithStatus:error.localizedDescription];
        });
        
    }];
    
}



- (void)deleteInsurance:(NSString *)insuranceId
{
    
    //  保险预约列表
    
     CustomAlertView *alert = [CustomAlertView alertViewWithTitle:@"删除预约" message:@"确定要删除该项预约吗?" btnTagClicked:^(NSInteger btnIndex) {
         
          if (btnIndex == 1) {
              
              UserRes *user = [CommonMethod getUser];
              if (!user) {
                  [[NSNotificationCenter defaultCenter]postNotificationName:NotificationCenterName_AlertLoginVC object:nil];
                  return;
              }
              NSDictionary *params = @{
                                       @"FKEY":[CommonMethod createMD5Key:@"INSURANCE_ID"],
                                       @"TOKEN":user.TOKEN,
                                       @"USERNAME":user.mobile,
                                       @"INSURANCE_ID":insuranceId
                                       
                                       };
              
              dispatch_async(dispatch_get_main_queue(), ^{
                  [SVProgressHUD showWithStatus:nil];
              });
              
              [[ZY_AfnNetManager shareInstance]postWithURL:Car_API_47 params:params md5Paraname:nil success:^(id  _Nullable response) {
                  
                  dispatch_async(dispatch_get_main_queue(), ^{
                      [SVProgressHUD dismiss];
                  });
                  [self fetchDataWithNet];
                  
                  
                  
              } fail:^(NSError * _Nonnull error) {
                  dispatch_async(dispatch_get_main_queue(), ^{
                      [SVProgressHUD showErrorWithStatus:error.localizedDescription];
                  });
                  
              }];
          }
     }cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    [alert show];
    
   
    
}


- (void)deleteMaintain:(NSString *)maintainId
{
    
    CustomAlertView *alert = [CustomAlertView alertViewWithTitle:@"删除预约" message:@"确定要删除该项预约吗?" btnTagClicked:^(NSInteger btnIndex) {
        if (btnIndex == 1) {
            //  保险预约列表
            UserRes *user = [CommonMethod getUser];
            if (!user) {
                [[NSNotificationCenter defaultCenter]postNotificationName:NotificationCenterName_AlertLoginVC object:nil];
                return;
            }
            NSDictionary *params = @{
                                     @"FKEY":[CommonMethod createMD5Key:@"MAINTAIN_ID"],
                                     @"TOKEN":user.TOKEN,
                                     @"USERNAME":user.mobile,
                                     @"MAINTAIN_ID":maintainId
                                     
                                     };
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [SVProgressHUD showWithStatus:nil];
            });
            
            [[ZY_AfnNetManager shareInstance]postWithURL:Car_API_50 params:params md5Paraname:nil success:^(id  _Nullable response) {
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    [SVProgressHUD dismiss];
                });
                [self fetchDataWithNet];
                
                
                
            } fail:^(NSError * _Nonnull error) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [SVProgressHUD showErrorWithStatus:error.localizedDescription];
                });
                
            }];
        }
    } cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    [alert show];
    
    
    
    
}

- (void)createUI
{
    self.mainTableView.frame  = CGRectMake(0, 0, BOUNDWIDTH, BOUNDHEIGHT-(IS_IPHONE_X?88:64));
    [self.mainTableView registerClass:[InsurancePointCell class] forCellReuseIdentifier:@"InsurancePointCell"];
      [self.mainTableView registerClass:[MaintainPointCell class] forCellReuseIdentifier:@"MaintainPointCell"];
   
}


#pragma mark ----UITableViewDelegate,UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.InsuranceAry.count  + self.MaintainAry.count;
}






-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 135;
}




- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.InsuranceAry.count > 0) {
        if (indexPath.row < self.InsuranceAry.count) {
            InsurancePointCell *cell = (InsurancePointCell *)[tableView dequeueReusableCellWithIdentifier:@"InsurancePointCell" forIndexPath:indexPath];
            
            [cell setData:self.InsuranceAry[indexPath.row]];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.resultBlock = ^(id  _Nonnull response) {
                [self deleteInsurance:response];
            };
            return cell;
        } else {
            MaintainPointCell *cell = (MaintainPointCell *)[tableView dequeueReusableCellWithIdentifier:@"MaintainPointCell" forIndexPath:indexPath];
            
            [cell setData:self.MaintainAry[indexPath.row-self.InsuranceAry.count]];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.resultBlock = ^(id  _Nonnull response) {
                        [self deleteMaintain:response];
            };
            return cell;
            
        }
    } else {
        
        MaintainPointCell *cell = (MaintainPointCell *)[tableView dequeueReusableCellWithIdentifier:@"MaintainPointCell" forIndexPath:indexPath];
        
        [cell setData:self.MaintainAry[indexPath.row-self.InsuranceAry.count]];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.resultBlock = ^(id  _Nonnull response) {
                        [self deleteMaintain:response];
        };
        return cell;
        
    }
 
    
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
